<template>
  <div class="absolute w-full top-0 left-0 flex items-center justify-between">
    <div class="w-1/6 h-72 mt-5">
      <v-chart class="chart" :option="option1" autoresize />
    </div>
    <div class="w-1/6 h-72 mt-5">
      <v-chart class="chart" :option="option2" autoresize />
    </div>
    <div class="w-1/6 h-72 mt-5">
      <v-chart class="chart" :option="option3" autoresize />
    </div>
    <div class="w-1/6 h-72 mt-5">
      <v-chart class="chart" :option="option5" autoresize />
    </div>
    <div class="w-1/6 h-72 mt-5 pr-4">
      <v-chart class="chart" :option="option6" autoresize />
    </div>
    <div class="w-1/6 h-72 mt-5">
      <v-chart class="chart" :option="option4" autoresize />
    </div>
  </div>
  <div class="absolute bottom-0 w-full h-96 flex">
    <div class="w-1/3 h-84 px-8 mt-10">
      <v-chart class="chart" :option="chartOption" autoresize />
    </div>
    <div class="w-1/3 h-84 px-8 mt-10">
      <v-chart class="chart" :option="chartOption2" autoresize />
    </div>
    <div class="w-1/3 h-84 px-8 mt-10">
      <v-chart class="chart" :option="chartOption3" autoresize />
    </div>
    <Title title="电流" class="absolute left-[370px] bottom-0"></Title>
    <Title title="轧制力" class="absolute left-[1230px] bottom-0"></Title>
    <Title title="轧辊速度" class="absolute left-[2080px] bottom-0"></Title>
  </div>
</template>

<script setup>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PictorialBarChart } from 'echarts/charts'
import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { graphic } from 'echarts'
import VChart from 'vue-echarts'
import Title from './Title.vue'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { getL1Data, getChartData } from '@/api/api'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PictorialBarChart,
  TooltipComponent,
  GridComponent,
  LegendComponent,
])

// 时间标签将从接口数据中动态生成
const timeLabels = ref([])

// 公共坐标与网格样式（深蓝背景适配）
const baseAxes = computed(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      if (params && params.length > 0) {
        const timestamp = params[0].axisValue
        // 将ISO格式时间戳转换为 YYYY-MM-DD HH:mm:ss 格式
        const date = new Date(timestamp)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        const timeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

        let result = `<div style="margin-bottom: 5px; font-weight: bold;">${timeStr}</div>`
        params.forEach((param) => {
          result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: ${param.value}
          </div>`
        })
        return result
      }
      return ''
    },
  },
  grid: { left: '13%', top: '12%', right: '3%', bottom: '5%', containLabel: true },
  xAxis: {
    type: 'category',
    data: timeLabels.value,
    boundaryGap: true,
    axisTick: { show: false },
    axisLabel: {
      interval: 0,
      rotate: -35,
      overflow: 'truncate',
      width: 50,
      hideOverlap: true,
      formatter: (value) => {
        // 格式化时间戳显示
        if (value) {
          const date = new Date(value)
          const hh = String(date.getHours()).padStart(2, '0')
          const mm = String(date.getMinutes()).padStart(2, '0')
          return `${hh}:${mm}`
        }
        return value
      },
      textStyle: { show: true, color: '#ffffff', fontSize: 12 },
    },
    axisLine: {
      symbol: ['none', 'arrow'],
      symbolSize: [10, 15],
      symbolOffset: [0, 0],
      lineStyle: { width: 2, color: 'rgba(255,255,255,0.6)' },
    },
  },
}))

const buildYAxis = (name) => ({
  name,
  nameTextStyle: { color: '#ffffff', padding: [0, 0, 6, 0] },
  type: 'value',
  splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.2)' } },
  axisLine: {
    show: true,
    symbol: ['none', 'arrow'],
    symbolSize: [10, 15],
    symbolOffset: [0, 0],
    lineStyle: { width: 2, color: 'rgba(255,255,255,0.6)' },
  },
  axisLabel: { textStyle: { show: true, color: '#ffffff', fontSize: 12 } },
})

const buildLine = (name, data, color, withArea = true) => ({
  name,
  type: 'line',
  data,
  smooth: true,
  symbol: 'circle',
  symbolSize: 0,
  lineStyle: { width: 2, type: 'solid', color },
  itemStyle: { borderWidth: 5, borderColor: color, color },
  areaStyle: withArea
    ? {
        color: new graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: `${color}CC` },
          { offset: 1, color: `${color}1A` },
        ]),
      }
    : undefined,
})

// 图表数据管理
const chartDataMap = ref({})
const len = computed(() => timeLabels.value.length)

// 需要请求的asset_alias列表
const assetAliases = [
  '/1880/FMC/ITG/PY/FMD/StripTemp_1_Act', // 出口温度A
  '/1880/FMC/ITG/PY/FMD/StripTemp_2_Act', // 出口温度B
  '/1880/FMC/L2/ACT/F7D/Thick', // 带钢厚度
  '/1880/FMC/L2/ACT/F7D/Width', // 带钢宽度
  '/1880/RMC/L2/ACT/R2_P1/Temp_Ex', // R2出口温度2-1
  '/1880/RMC/L2/ACT/R2_P3/Temp_Ext', // R2出口温度2-3
  '/1880/RMC/L2/ACT/R2_P5/Temp_Ext', // R2出口温度2-5
  '/1880/FMC/ITG/PY/CS/StripTemp_N001', // 入口温度1
  '/1880/FMC/ITG/PY/CS/StripTemp_N002', // 入口温度2
  '/1880/RMC/L2/ACT/R2_P1/Width', // 带钢宽度2-1
  '/1880/RMC/L2/ACT/R2_P3/Width', // 带钢宽度2-3
  '/1880/RMC/L2/ACT/R2_P5/Width', // 带钢宽度2-5
]

// 获取图表数据
const fetchChartData = async () => {
  try {
    const newDataMap = {}
    const allTimestamps = new Set()

    // 按asset_alias分组数据
    assetAliases.forEach((alias) => {
      newDataMap[alias] = []
    })

    // 为每个asset_alias单独发送请求
    const requests = assetAliases.map(async (alias) => {
      try {
        const res = await getChartData({ asset_alias: alias })
        if (res && Array.isArray(res.data)) {
          res.data.forEach((item) => {
            if (newDataMap[item.asset_alias]) {
              newDataMap[item.asset_alias].push({
                timestamp: item.timestamp,
                value: item.value,
              })
              allTimestamps.add(item.timestamp)
            }
          })
        }
      } catch (error) {
        console.error(`Error fetching data for ${alias}:`, error)
      }
    })

    // 等待所有请求完成
    await Promise.all(requests)

    // 生成时间标签（按时间排序）
    timeLabels.value = Array.from(allTimestamps).sort()

    // 为每个asset_alias生成时间序列数据
    assetAliases.forEach((alias) => {
      const dataPoints = newDataMap[alias] || []
      const timeSeriesData = []

      // 为每个时间点生成数据
      timeLabels.value.forEach((timestamp) => {
        const dataPoint = dataPoints.find((dp) => dp.timestamp === timestamp)
        timeSeriesData.push(dataPoint ? dataPoint.value : 0)
      })

      chartDataMap.value[alias] = timeSeriesData
    })
  } catch (e) {
    console.error('getChartData error:', e)
  }
}

// 生成空数据数组的函数
const genEmpty = () => Array.from({ length: len.value }, () => 0)

// 1. 出口温度A、B
const option1 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('出口温度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine(
      '出口温度A',
      chartDataMap.value['/1880/FMC/ITG/PY/FMD/StripTemp_1_Act'] || genEmpty(),
      '#1AC9FF',
    ),
    buildLine(
      '出口温度B',
      chartDataMap.value['/1880/FMC/ITG/PY/FMD/StripTemp_2_Act'] || genEmpty(),
      '#FFD166',
    ),
  ],
}))

// 2. 带钢厚度
const option2 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('带钢厚度'),
  legend: { show: false },
  series: [
    buildLine(
      '带钢厚度',
      chartDataMap.value['/1880/FMC/L2/ACT/F7D/Thick'] || genEmpty(),
      '#4ECDC4',
    ),
  ],
}))

// 3. 带钢宽度
const option3 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('带钢宽度'),
  legend: { show: false },
  series: [
    buildLine(
      '带钢宽度',
      chartDataMap.value['/1880/FMC/L2/ACT/F7D/Width'] || genEmpty(),
      '#A29BFE',
    ),
  ],
}))

// 4. R2出口温度2-1、2-3、2-5
const option4 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('R2出口温度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine('2-1', chartDataMap.value['/1880/RMC/L2/ACT/R2_P1/Temp_Ex'] || genEmpty(), '#06D6A0'),
    buildLine(
      '2-3',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P3/Temp_Ext'] || genEmpty(),
      '#EF476F',
    ),
    buildLine(
      '2-5',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P5/Temp_Ext'] || genEmpty(),
      '#FF9F1C',
    ),
  ],
}))

// 5. 入口温度1、2
const option5 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('入口温度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine(
      '入口温度1',
      chartDataMap.value['/1880/FMC/ITG/PY/CS/StripTemp_N001'] || genEmpty(),
      '#118AB2',
    ),
    buildLine(
      '入口温度2',
      chartDataMap.value['/1880/FMC/ITG/PY/CS/StripTemp_N002'] || genEmpty(),
      '#FF9F1C',
    ),
  ],
}))

// 6. 带钢宽度2-1、2-3、2-5
const option6 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('带钢宽度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine('2-1', chartDataMap.value['/1880/RMC/L2/ACT/R2_P1/Width'] || genEmpty(), '#F72585'),
    buildLine('2-3', chartDataMap.value['/1880/RMC/L2/ACT/R2_P3/Width'] || genEmpty(), '#9B59B6'),
    buildLine('2-5', chartDataMap.value['/1880/RMC/L2/ACT/R2_P5/Width'] || genEmpty(), '#E74C3C'),
  ],
}))

//---------------------------------F7-F1电流、轧制力、轧辊速度---------------------------------------
// 数据管理
const dataMap = ref({})

const fetchData = async () => {
  try {
    const res = await getL1Data()
    const map = {}
    if (res && Array.isArray(res.data)) {
      for (const item of res.data) {
        map[item.asset_alias] = item.value
      }
    }
    dataMap.value = map
  } catch (e) {
    console.error('getL1Data error:', e)
  }
}

let timer = null
let chartTimer = null

onMounted(() => {
  fetchData()
  fetchChartData()
  timer = setInterval(fetchData, 10000)
  chartTimer = setInterval(fetchChartData, 10000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (chartTimer) clearInterval(chartTimer)
})

const vRaw = (alias) => dataMap.value[alias]

const formatNumber = (v, precision = 1) => {
  if (v === null || v === undefined) return 0
  const n = Number(v)
  if (!Number.isFinite(n)) return 0
  return Number.isInteger(n) ? n : parseFloat(n.toFixed(precision))
}

const vf = (alias) => formatNumber(vRaw(alias))

// 获取F7-F1的实时数据
const getCurrentData = () => {
  const stands = ['F7', 'F6', 'F5', 'F4', 'F3', 'F2', 'F1']
  const current = [] // 电流
  const force = [] // 轧制力
  const speed = [] // 轧辊速度

  stands.forEach((stand) => {
    const standNum = stand.substring(1)
    // 电流：保留小数1位
    const currentValue = vRaw(`/1880/FMC/${stand}/MOTOR/Cur_Act`)
    // current.push(formatNumber(currentValue, 1))
    current.push(Math.max(formatNumber(currentValue, 1), 0))

    // 轧制力：先除以10，再保留小数2位
    const forceValue = vRaw(`/1880/FMC/${stand}/SDS/LCRF_Total_Fbk`)
    // force.push(formatNumber(forceValue / 10, 2))
    force.push(Math.max(formatNumber(forceValue / 10, 2), 0))

    // 轧辊速度：保留小数1位
    const speedValue = vRaw(`/1880/FMC/${stand}/SSF/RollSpeed_Fbk`)
    // speed.push(formatNumber(speedValue / 1000, 1))
    speed.push(Math.max(formatNumber(speedValue / 1000, 1), 0))
  })

  return { current, force, speed }
}

const categories = ['F7', 'F6', 'F5', 'F4', 'F3', 'F2', 'F1']

const baseBar = (name, data, colors) => ({
  name,
  type: 'bar',
  barWidth: 40,
  barGap: '-100%',
  showBackground: true,
  backgroundStyle: { color: 'rgba(0,111,177, 0.3)' },
  itemStyle: {
    color: {
      x: 0,
      y: 0,
      x2: 0,
      y2: 1,
      colorStops: [
        { offset: 0, color: colors[0] },
        { offset: 1, color: colors[1] },
      ],
    },
  },
  zlevel: 1,
  data,
})

const topCapPositive = (data) => ({
  type: 'pictorialBar',
  silent: true,
  symbolSize: [40, 10],
  symbolOffset: [0, -6],
  symbolPosition: 'end',
  zlevel: 3,
  itemStyle: { color: '#fff', shadowColor: 'rgba(255,255,255,1)', shadowBlur: 15 },
  tooltip: { show: false },
  data: data.map((v) => (v >= 0 ? v : null)),
})

const topCapNegative = (data) => ({
  type: 'pictorialBar',
  silent: true,
  symbolSize: [40, 10],
  symbolOffset: [0, 6],
  symbolPosition: 'end',
  zlevel: 3,
  itemStyle: { color: '#fff', shadowColor: 'rgba(255,255,255,1)', shadowBlur: 15 },
  tooltip: { show: false },
  data: data.map((v) => (v < 0 ? v : null)),
})

const bottomCapPositive = (data, color = '#0c76aa') => ({
  type: 'pictorialBar',
  silent: true,
  symbolSize: [40, 10],
  symbolOffset: [0, 7],
  symbolPosition: 'start',
  zlevel: 2,
  itemStyle: { color },
  tooltip: { show: false },
  data: data.map((v) => (v >= 0 ? 0 : null)),
})

const bottomCapNegative = (data, color = '#0c76aa') => ({
  type: 'pictorialBar',
  silent: true,
  symbolSize: [40, 10],
  symbolOffset: [0, -6],
  symbolPosition: 'end',
  zlevel: 2,
  itemStyle: { color },
  tooltip: { show: false },
  data: data.map((v) => (v < 0 ? 0 : null)),
})

const getBarBaseOption = (minVal, maxVal, interval) => ({
  grid: { left: 80, bottom: 40, right: 80, top: 80, containLabel: true },
  legend: { show: false },
  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  xAxis: {
    type: 'category',
    axisTick: { show: false },
    axisLine: {
      symbol: ['none', 'arrow'],
      symbolSize: [10, 10],
      symbolOffset: [0, 10],
      lineStyle: { color: '#0B5EA0' },
    },
    axisLabel: { margin: 20, textStyle: { color: 'rgb(183,227,252)' } },
    data: categories,
  },
  yAxis: [
    {
      type: 'value',
      min: minVal,
      max: maxVal,
      interval: interval,
      axisTick: { show: false },
      axisLine: { show: true, lineStyle: { color: '#0C5B9B' } },
      splitLine: { show: true, lineStyle: { color: '#11456F' } },
      splitArea: { show: true, areaStyle: { color: 'rgba(36,85,134,.2)' } },
      axisLabel: { margin: 20, textStyle: { color: '#78C0E6' } },
    },
  ],
})

function getAdaptiveScale(values) {
  // 过滤掉 null / undefined，防止异常
  const validValues = values.filter((v) => typeof v === 'number' && !isNaN(v))

  const maxVal = Math.max(...validValues, 0)
  const range = Math.abs(maxVal)

  // 动态放大 20%
  const adjustedMax =
    range === 0 ? 0 : range < 100 ? Math.ceil(range * 1.2) : Math.ceil((range * 1.2) / 100) * 100

  const adjustedMin = 0 // ✅ 只显示正轴
  const adjustedInterval = adjustedMax > 0 ? Math.max(1, Math.round(adjustedMax / 3 / 10) * 10) : 1

  return { adjustedMin, adjustedMax, adjustedInterval }
}

// 电流图表 (chartOption)
const chartOption = computed(() => {
  const { current } = getCurrentData()
  const { adjustedMin, adjustedMax, adjustedInterval } = getAdaptiveScale(current)

  return {
    ...getBarBaseOption(adjustedMin, adjustedMax, adjustedInterval),
    series: [
      baseBar('电流', current, ['#006caf', '#04f2ff']),
      topCapPositive(current),
      topCapNegative(current),
      bottomCapPositive(current, '#0c76aa'),
      bottomCapNegative(current, '#0c76aa'),
    ],
  }
})

// 轧制力图表 (chartOption2)
const chartOption2 = computed(() => {
  const { force } = getCurrentData()
  const { adjustedMin, adjustedMax, adjustedInterval } = getAdaptiveScale(force)

  return {
    ...getBarBaseOption(adjustedMin, adjustedMax, adjustedInterval),
    series: [
      baseBar('轧制力', force, ['#0a2b71', '#4ecdc4']),
      topCapPositive(force),
      topCapNegative(force),
      bottomCapPositive(force, '#0c76aa'),
      bottomCapNegative(force, '#0c76aa'),
    ],
  }
})

// 轧辊速度图表 (chartOption3)
const chartOption3 = computed(() => {
  const { speed } = getCurrentData()
  const { adjustedMin, adjustedMax, adjustedInterval } = getAdaptiveScale(speed)

  return {
    ...getBarBaseOption(adjustedMin, adjustedMax, adjustedInterval),
    series: [
      baseBar('轧辊速度', speed, ['#45b7d1', '#96ceb4']),
      topCapPositive(speed),
      topCapNegative(speed),
      bottomCapPositive(speed, '#0c76aa'),
      bottomCapNegative(speed, '#0c76aa'),
    ],
  }
})
</script>

<style lang="scss" scoped>
.gradient-text {
  background: linear-gradient(to bottom, #dce0ff, #06fcff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  /* 兼容 Firefox */
  background-clip: text;
  color: transparent;
}
.chart {
  width: 100%;
  height: 100%;
}
</style>
